package org.balabala.gateway.config;

import org.balabala.gateway.redis.SessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SessionInterceptor implements  HandlerInterceptor {
    @Autowired
    public SessionManager sessionManager;
    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            Cookie[] cookies = request.getCookies();
            Long userId = (Long) request.getSession().getAttribute("userId");
            if(userId==null){
                return false;
            }else{
                if (!sessionManager.getSession(userId).isEmpty()){
                    return false;
                }
            }
            response.sendRedirect("/index.html");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;//如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        //如果设置为true时，请求将会继续执行后面的操作
    }
}